<?php

namespace app\admin\services;

use app\common\model\Member;
use app\common\model\OnlineWriteFlow;
use app\common\services\BaseService;
use app\common\util\DateTimeUtil;
use app\common\util\weixin\TemplateMessage;

class OnlineWriteService extends BaseService
{

    public function setAuth($data)
    {
        try {
            $id = intval($data['id']);
            $status = intval($data['status']);
            if ($status == 2 && empty($data['reason'])) {
                return [false, '拒绝理由不能为空'];
            }
            $reason = !empty($data['reason']) ? trim($data['reason']) : '';
            $entry = $this->getModelInstance()->where(['id' => $id])->find();
            if (!empty($entry)) {
                if ($entry['status'] == 1) {
                    return [false, '不能再审核已通过的记录'];
                }
                OnlineWriteFlow::instance()->add([
                    'status' => $status,
                    'content' => $reason,
                    'create_time' => DateTimeUtil::now(),
                    'online_write_id' => $id
                ]);
                $this->getModelInstance()->where(['id' => $id])->setField('status', $status);

                if ($status == 1) { // 审核通过消息
                    $member_id = $entry['member_id'];
                    if (!empty($member_id)) {
                        $openid = Member::instance()->where(['id' => $member_id])->getField('openid');
                        if (!empty($openid)) {
                            //预约成功通知
                            TemplateMessage::sendTemplateMessage([
                                'first' => [
                                    'value' => '您的在线填表审核已通过'
                                ],
                                'keyword1' => [
                                    'value' => '房屋租赁'
                                ],
                                'keyword2' => [
                                    'value' => '请尽快来社区办理'
                                ],
                                'remark' => [
                                    'value' => "\n".'感谢您的使用，如有疑问，请致电' . ccnn_sys_setting('客服电话', ''),
                                    'color'=>'#173177'
                                ]
                            ], $openid, 'vngvaFWep3Y4UPo7i5ZZaA3Bu5X6L8mL3ZXuscmpnpE',
                                U('weixin/OnlineWrite/workResult', [
                                    'id' => $id
                                ], true, true));
                        }
                    }
                } elseif ($status == 2) { //审核拒绝
                    $member_id = $entry['member_id'];
                    if (!empty($member_id)) {
                        $openid = Member::instance()->where(['id' => $member_id])->getField('openid');
                        if (!empty($openid)) {
                            //预约成功通知
                            TemplateMessage::sendTemplateMessage([
                                'first' => [
                                    'value' => '您的在线填表审核未通过',
                                    'color'=>'#ff0000'
                                ],
                                'keyword1' => [
                                    'value' => '房屋租赁'
                                ],
                                'keyword2' => [
                                    'value' => $reason
                                ],
                                'remark' => [
                                    'value' => "\n".'感谢您的使用，如有疑问，请致电' . ccnn_sys_setting('客服电话', ''),
                                    'color'=>'#173177'
                                ]
                            ], $openid, 'vngvaFWep3Y4UPo7i5ZZaA3Bu5X6L8mL3ZXuscmpnpE',
                                U('weixin/OnlineWrite/workResult', [
                                    'id' => $id
                                ], true, true));
                        }
                    }
                }
            }
            return [true, '操作成功'];
        } catch (\Exception $ex) {
            return [false, $ex->getMessage()];
        }
    }

    public function download($id)
    {
        if ($id) {
            $entry = $this->_getViewInstance()->find($id);
            require_once APP_PATH . '../lib/phpexcel/PHPExcel.php';
            $temPath = APP_PATH . 'admin/data/template.xls';
            if (!file_exists($temPath) || !is_readable($temPath)) {
                echo '找不到模板文件或者文件不可读';
                exit;
            }

            $objReader = new \PHPExcel_Reader_Excel5();
            $objPHPExcel = $objReader->load($temPath);

            $sheet = $objPHPExcel->setActiveSheetIndex(0);
            $sheet->setCellValue('K4', $entry['lessor_name']);

            if ($entry['lessor_type'] == 0) { //单位
                $sheet->setCellValue('H5', $entry['lessor_identity']);
                $sheet->setCellValue('F4', '  ☑ 单位             ☐ 个人');
            } else if ($entry['lessor_type'] == 1) { // 个人
                $sheet->setCellValue('H6', $entry['lessor_identity']);
                $sheet->setCellValue('F4', '  ☐ 单位             ☑ 个人');
            }
            $sheet->setCellValue('F7', $entry['lessor_address']);
            $sheet->setCellValue('F8', $entry['lessor_postcode']);
            $sheet->setCellValue('N8', $entry['lessor_telephone']);
            $sheet->setCellValue('F9', $entry['owner_name']);
            $sheet->setCellValue('N9', $entry['owner_identity']);
            /**
             * 产权（使用权）材料名称及号码
             */
            $sheet->setCellValue('F10', $entry['material_name']);
            //受委托人
            $sheet->setCellValue('F11', $entry['lease_trustee']);
            $sheet->setCellValue('N11', $entry['lease_trustee_phone']);
            $sheet->setCellValue('F12', $entry['lease_trustee_identity']);
            //承租人（个人）
            $sheet->setCellValue('F13', $entry['renter_name']);
            $sheet->setCellValue('F14', $entry['renter_identity']);
            //通信地址
            $sheet->setCellValue('F15', $entry['renter_address']);
            $sheet->setCellValue('F16', $entry['renter_postcode']);
            //承租人电话
            $sheet->setCellValue('N16', $entry['renter_telephone']);
            /**
             * 承租受委托人
             */
            $sheet->setCellValue('F17', $entry['rent_trustee']);

            $sheet->setCellValue('N17', $entry['rent_trustee_phone']);
            $sheet->setCellValue('F18', $entry['rent_trustee_identity']);
            //房屋坐落地址
            $sheet->setCellValue('F19', $entry['lease_area'] . ' ' . $entry['lease_address']);
            //租赁面积（㎡）
            $sheet->setCellValue('F20', $entry['lease_measure']);
            //月租金（元）
            $sheet->setCellValue('N20', $entry['lease_price']);
            //租赁期限  lease_start_date   lease_end_date
            $start_date = explode('-', $entry['lease_start_date']);
            $end_date = explode('-', $entry['lease_end_date']);
            $sheet->setCellValue('F21', "{$start_date[0]} 年 {$start_date[1]} 月 {$start_date[2]} 日至 {$end_date[0]} 年 {$end_date[1]} 月 {$end_date[2]} 日");

            $filename = $entry['lessor_name'];
            header("Content-type:application/vnd.ms-excel");  //设置内容类型
            header("Content-Disposition:attachment;filename=$filename.xls");  //文件下载
            header('Cache-Control: max-age=1');

            // If you're serving to IE over SSL, then the following may be needed
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header('Pragma: public'); // HTTP/1.0
            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save('php://output');

        }
    }
}